<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="题目类型" prop="subjectType">
        <el-cascader
          clearable
          placeholder="题目类型"
          @change="editCascader"
          :props="{ value: 'id',label:'typeName'}"
          style="width: 100%"
          v-model="subjectTypeTest"
          :options="subjectTypeOptions"
          :show-all-levels="false"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="题目难度" prop="subjectDifficlty">
        <el-cascader
          clearable
          placeholder="题目难度"
          @change="editDifficlty"
          :props="{ value: 'id',label:'difficultyName' }"
          style="width: 100%"
          v-model="subjectDifficltyTest"
          :options="subjectDifficltyOptions"
          :show-all-levels="false"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="标题" prop="titleName">
        <el-input v-model="dataForm.titleName" type="textarea" placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item label="题目描述" prop="subiectDesc">
        <el-input v-model="dataForm.subiectDesc" type="textarea" placeholder="题目描述"></el-input>
      </el-form-item>
      <el-form-item label="标准答案" prop="standardAnswer">
        <el-input v-model="dataForm.standardAnswer" type="textarea" placeholder="标准答案"></el-input>
      </el-form-item>
      <span><b>题目限制:</b></span>
      <el-form-item label="时间限制" prop="timeLimit">
        <el-input v-model="dataForm.timeLimit" type="number" placeholder="时间限制"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addtags()">添加分组</el-button>
    <el-table
      :data="keyWord"
      style="width: 100%">
      <el-table-column
        prop="">
        <template slot-scope="obj">
          第{{obj.row.count}}组
          <el-tag
            :key="index"
            v-for="(item,index) in obj.row.keyWordName"
            v-if="item.keyWordName!=null"
            closable
            :disable-transitions="false"
            @close="handleClose(item,obj.row)">
            {{item.keyWordName}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="keyWordName"
            size="small"
            @keyup.enter.native="handleInputConfirm(obj.row)"
            @blur="handleInputConfirm(obj.row)">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
          <el-button  class="button-new-tag" size="small" @click="setweight(obj.row)">设置权重</el-button>
          {{obj.row.groups}}
          <el-input
            class="input-new-tag"
            v-if="inputVisible1"
            v-model.number="groups"
            size="small"
            @blur="changeWeight(obj.row)"
          >
          </el-input>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

<script>
  export default {
    data () {
      return {
        keyWord:[],
        dynamicTags:[],
        groups:'',
        count:0,
        inputVisible: false,
        inputVisible1: false,
        keyWordName: '',
        subjectTypeOptions:[],
        subjectDifficltyOptions:[],
        subjectTypeOptionsOne:[],
        subjectDifficltyOptionsOne:[],
        keywordList:[],
        visible: false,
        subjectTypeTest:'',
        subjectDifficltyTest:'',
        dataForm: {
          id: 0,
          subjectType: '',
          subjectDifficlty: '',
          titleName: '',
          standardAnswer: '',
          timeLimit: '',
          subiectDesc: '',
          isStart: '',
          beginData: '',
          endData: '',
         typeId:null,
         difficltyId:null
        },
        dataRule: {
          subjectType: [
            { required: true, message: '题目类型不能为空', trigger: 'blur' }
          ],
          subjectDifficlty: [
            { required: true, message: '题目难度不能为空', trigger: 'blur' }
          ],
          titleName: [
            { required: true, message: '标题不能为空', trigger: 'blur' }
          ],
          timeLimit: [
            { required: true, message: '时间限制不能为空', trigger: 'blur' }
          ],
          subiectDesc: [
            { required: true, message: '题目描述不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.findData();
    },
    methods: {
      editCascader(){
          var shu=this.subjectTypeTest[this.subjectTypeTest.length-1]
          this.dataForm.typeId=shu;
        for(var i=0;i<this.subjectTypeOptionsOne.length;i++){
          if(this.subjectTypeTest[0]===this.subjectTypeOptionsOne[i].id){
            this.dataForm.subjectType=this.subjectTypeOptionsOne[i]
          }
        }
      },
      editDifficlty(){
         var shu2=this.subjectDifficltyTest[this.subjectDifficltyTest.length-1];
        this.dataForm.difficltyId=shu2;
        for(var i=0;i<this.subjectDifficltyOptionsOne.length;i++){
          if(this.subjectDifficltyTest[0]===this.subjectDifficltyOptionsOne[i].id){
            this.dataForm.subjectDifficlty=this.subjectDifficltyOptionsOne[i]
          }
        }
      },
      editData(val){//处理流数据
        for (let i=0;i<val.length;i++){
          if (val[i].children.length === 0){
            val[i].children = undefined
          }else{
            this.editData(val[i].children)
          }
        }
        return val
      },
      async findData(){//页面加载获取数据
        this.$http({
          url: this.$http.adornUrl('/hope/reply/subjecttype/alls'),
          method: 'get'
        }).then(({data}) => {
          this.subjectTypeOptions = this.editData(data)
        })
        this.$http({
          url: this.$http.adornUrl('/hope/reply/subjecttype/all'),
          method: 'get'
        }).then(({data}) => {
          this.subjectTypeOptionsOne = data
        })
        await this.$http({
          url: this.$http.adornUrl('/hope/reply/subjectdifficulty/alls'),
          method: 'get'
        }).then(({data}) => {
          this.subjectDifficltyOptions = this.editData(data)
        })
        await this.$http({
          url: this.$http.adornUrl('/hope/reply/subjectdifficulty/all'),
          method: 'get'
        }).then(({data}) => {
          this.subjectDifficltyOptionsOne = data
        })
      },
      init (id) {
        if(id!=null && id!=''){
          this.dataForm.id = id || 0
          this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/reply/subject/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.subjectType = JSON.parse(data.subject.subjectType)
                this.dataForm.subjectDifficlty = JSON.parse(data.subject.subjectDifficlty)
                this.dataForm.titleName = data.subject.titleName
                this.dataForm.standardAnswer = data.subject.standardAnswer
                this.dataForm.timeLimit = data.subject.timeLimit
                this.dataForm.subiectDesc = data.subject.subiectDesc
                this.dataForm.isStart = data.subject.isStart
                this.dataForm.beginData = data.subject.beginData
                this.dataForm.endData = data.subject.endData
                //分词表
                this.keyWord=[]
                this.count=1
                this.keywordList=data.keyWordEntityList
                this.keywordList.forEach(res=>{
               
                  this.keyWord.push({
                    id: res.id,
                    count: this.count++,
                    groups: res.groups,
                    keyWordName:JSON.parse(res.keyWordName)
                  })
                })
                this.subjectTypeTest = []
                this.subjectDifficltyTest = []
                this.subjectTypeTest.push(JSON.parse(data.subject.subjectType).id)
                this.subjectDifficltyTest.push(JSON.parse(data.subject.subjectDifficlty).id)

              }
            })
          }
        })
        }else{
          this.dataForm = {}
          this.keyWord=[]
          this.subjectTypeTest=[]
          this.subjectDifficltyTest=[]
          this.count = 0;
          this.keyWord = []
        }
        this.visible = true
        
      },
      // 表单提交
      dataFormSubmit () {
        let keyWord = []
          this.keyWord.forEach(res=>{
            keyWord.push({
              id:res.id,
              keyWordName:JSON.stringify(res.keyWordName),
              groups:res.groups
            })
          })
        if(this.dataForm.id==undefined){//添加
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.$http({
                url: this.$http.adornUrl(`/reply/subject/save`),
                method: 'post',
                data: this.$http.adornData({
                  'id': this.dataForm.id || undefined,
                  'subjectType': JSON.stringify(this.dataForm.subjectType),
                  'subjectDifficlty': JSON.stringify(this.dataForm.subjectDifficlty),
                  'titleName': this.dataForm.titleName,
                  'standardAnswer': this.dataForm.standardAnswer,
                  'timeLimit': this.dataForm.timeLimit,
                  'subiectDesc': this.dataForm.subiectDesc,
                  'isStart': this.dataForm.isStart,
                  'beginData': this.dataForm.beginData,
                  'endData': this.dataForm.endData,
                  'keyWordEntityList': keyWord,
                  'typeId':this.dataForm.typeId,
                  'difficltyId':this.dataForm.difficltyId
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(data.msg)
                }
              })
            }
          })
        }else{//修改
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.$http({
                //url: this.$http.adornUrl(`/reply/subject/${!this.dataForm.id ? 'save' : 'update'}`),
                url: this.$http.adornUrl(`/reply/subject/update`),
                method: 'post',
                data: this.$http.adornData({
                  'id': this.dataForm.id || undefined,
                  'subjectType': JSON.stringify(this.dataForm.subjectType),
                  'subjectDifficlty': JSON.stringify(this.dataForm.subjectDifficlty),
                  'titleName': this.dataForm.titleName,
                  'standardAnswer': this.dataForm.standardAnswer,
                  'timeLimit': this.dataForm.timeLimit,
                  'subiectDesc': this.dataForm.subiectDesc,
                  'isStart': this.dataForm.isStart,
                  'beginData': this.dataForm.beginData,
                  'endData': this.dataForm.endData,
                  'keyWordEntityList': keyWord,
                  'typeId':this.dataForm.typeId,
                  'difficltyId':this.dataForm.difficltyId
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(data.msg)
                }
              })
            }
          })
        }
      },
      //动态标签的方法
      handleClose(item,row) {
        row.keyWordName.splice(row.keyWordName.indexOf(item), 1);
      },
      showInput() {
        this.inputVisible = true;
      },
      handleInputConfirm(row) {
        let keyWordName = this.keyWordName;
        if (keyWordName) {
          row.keyWordName.push({
            keyWordName: keyWordName
          });
        }
        this.inputVisible = false;
        this.keyWordName = '';
      },
      addtags(){
        this.count++;
        this.keyWord.push({
          count:this.count,
          keyWordName:[],
          groups:null
        })
      },
      setweight(row){
        this.inputVisible1=true
      },
      changeWeight(row){
        row.groups=this.groups
        this.inputVisible1=false
        this.inputVisible1=false
        this.groups=''
      }
    }
  }
</script>
